/**
 * Create by CaoWenjian
 *
 * @copyRight: 2018
 **/
package com.bjboot.caocao.common.utils;

import com.bjboot.caocao.common.config.Constant;
import com.bjboot.caocao.common.domain.ColumnDO;
import com.bjboot.caocao.common.domain.TableDO;
import com.bjboot.caocao.common.exception.BJException;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 *@Description: 代码生成工具类
 *@Author 操文健
 *@Date 2018-09-03 下午7:03
 *@Version 1.0
 **/
public class GenUtils {


    /**
     * 生成对应的模板文件
     * @param table
     * @param columns
     * @param zip
     */
    public static void generatorCode(Map<String, String> table, List<Map<String, String>> columns, ZipOutputStream zip) {
        // 加载配置信息
        Configuration config = getConfig();

        // 组装表的信息
        TableDO tableDO = new TableDO();
        tableDO.setTableName(table.get("tableName"));
        tableDO.setComments(table.get("tableComment"));
        // 表名转换为java类名
        String className = tableToJava(tableDO.getTableName(), config.getString("tablePrefix"), config.getString("autoRemovePre"));
        tableDO.setClassName(className);
        tableDO.setClassname(StringUtils.uncapitalize(className));

        // 开始处理列信息
        List<ColumnDO> columnDOList = new ArrayList<ColumnDO>();
        for (Map<String, String> column : columns) {
            ColumnDO columnDO = new ColumnDO();
            columnDO.setColumnName(column.get("columnName"));
            columnDO.setDataType(column.get("dataType"));
            columnDO.setComments(column.get("columnComment"));
            columnDO.setExtra(column.get("extra"));

            //列名转换成Java属性名
            String attrName = columnToJava(columnDO.getColumnName());
            columnDO.setAttrName(attrName);
            columnDO.setAttrname(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnDO.getDataType(), "unknowType");
            columnDO.setAttrType(attrType);

            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableDO.getPk() == null) {
                tableDO.setPk(columnDO);
            }

            columnDOList.add(columnDO);
        }
        tableDO.setColumns(columnDOList);

        //没主键，则第一个字段为主键
        if (tableDO.getPk() == null) {
            tableDO.setPk(tableDO.getColumns().get(0));
        }

        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        //封装模板数据
        Map<String, Object> map = new HashMap<>(16);
        map.put("tableName", tableDO.getTableName());
        map.put("comments", tableDO.getComments());
        map.put("pk", tableDO.getPk());
        map.put("className", tableDO.getClassName());
        map.put("classname", tableDO.getClassname());
        map.put("pathName", config.getString("package").substring(config.getString("package").lastIndexOf(".") + 1));
        map.put("columns", tableDO.getColumns());
        map.put("package", config.getString("package"));
        map.put("author", config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
          // 渲染模板，将数据整合到模板中
            StringWriter stringWriter = new StringWriter();
            Template template1 = Velocity.getTemplate(template, Constant.ENCODING_UTF8);
            template1.merge(context, stringWriter); // 将数据context整合到加载到模板中

            // 开始将数据整合带压缩包中
            String fileFullName = getFileName(template, tableDO.getClassname(), tableDO.getClassName(),
                    config.getString("package").substring(config.getString("package").lastIndexOf(".") + 1));

            // 将没个模板整合到数据装载到zip中
            try {
                zip.putNextEntry(new ZipEntry(fileFullName));
                IOUtils.write(stringWriter.toString(), zip, Constant.ENCODING_UTF8);
                IOUtils.closeQuietly(stringWriter);
                zip.closeEntry();
            } catch (IOException e) {
                throw new BJException("组装模板整合数据出现异常，对应到表明：" + tableDO.getTableName(), e);
            }
        }
    }

    /**
     * 根据类名，前缀，是否自动移除前缀进行生成对应的类名
     * @param tableName
     * @param tablePrefix
     * @param autoRemovePre
     * @return
     */
    private static String tableToJava(String tableName, String tablePrefix, String autoRemovePre) {
        if (Constant.AUTO_REMOVE_PREFIX.equals(autoRemovePre)) {
            tableName = tableName.substring(tableName.indexOf(tablePrefix) + 1);
        }

        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replace(tablePrefix, "");
        }
        return  columnToJava(tableName);
    }

    /**
     * 列名转换为java对应的属性名称
     * @param columnName
     * @return
     */
    private static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 获取文件名称
     * @param template 模板集合
     * @param classname 类名小写
     * @param className 类名大写
     * @param packageName 包名
     * @return
     */
    public static String getFileName(String template, String classname, String className, String packageName) {
        // 包根目录路径
        String packagePath = "main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            // 路径追加各自自定义的路径信息
            packagePath = packageName.replace(".", File.separator) + File.separator;
        }

        // TODO 需要对不同对模板进行不同对分析，创建不同的package名称
        // 根据各自的模板组装不同的对应文件名称
        if (template.contains("Mapper.xml.vm")) {
            return "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + packageName + File.separator + className + "Mapper.xml";
        }

        return null;
    }

    /**
     * 加载文件的配置信息
     * @return
     */
    public static Configuration getConfig() {
        try {
            // 读取配置文件，生成代码对应的properties文件信息
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new BJException("获取配置文件失败...", e);
        }
    }

    /**
     * 创建加载模板的list集合信息
     * @return
     */
    public static List<String> getTemplates() {
        //TODO 添加对应的模板所在位置进行解析创建
        List<String> templates = new ArrayList<String>();
        //templates.add("templates/common/generator/domain.java.vm");
        //templates.add("templates/common/generator/Dao.java.vm");
        //templates.add("templates/common/generator/Mapper.java.vm");
        templates.add("templates/common/generator/Mapper.xml.vm");
        /*templates.add("templates/common/generator/Service.java.vm");
        templates.add("templates/common/generator/ServiceImpl.java.vm");
        templates.add("templates/common/generator/Controller.java.vm");
        templates.add("templates/common/generator/list.html.vm");
        templates.add("templates/common/generator/add.html.vm");
        templates.add("templates/common/generator/edit.html.vm");
        templates.add("templates/common/generator/list.js.vm");
        templates.add("templates/common/generator/add.js.vm");
        templates.add("templates/common/generator/edit.js.vm");
        templates.add("templates/common/generator/menu.sql.vm");*/
        return templates;
    }
}
